<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\UnauthorizedException;
use Illuminate\Validation\ValidationException;
use League\OAuth2\Server\Exception\OAuthServerException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        UnauthorizedException::class,
        OAuthServerException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function report(Throwable $e)
    {
        try {
            $this->shouldReport($e) and \ExceptionNotifier::report($e);
        } catch (\Exception $e) {
        }
        return parent::report($e);
    }

    /**
     * 覆盖全局验证器报错
     * @param ValidationException $e
     * @param $request
     * @return JsonResponse
     */
    public function convertValidationExceptionToResponse(ValidationException $e, $request): JsonResponse
    {
        $messages = [];
        foreach ($e->errors() as $error) {
            foreach ($error as $item) {
                $messages[] = $item;
            }
        }
        return response()->json([
            'msg'  => implode(';', $messages),
            'code' => 422,
        ]);
    }

    public function render($request, Throwable $e)
    {
        if ($e instanceof UnauthorizedException) {
            return response()->json([
                'msg'  => "Unauthorized",
                'code' => 401,
            ]);
        }

        if ($e instanceof ThrottleRequestsException) {
            return response()->json([
                'msg'  => "操作频繁，请稍后再试！",
                'code' => $e->getStatusCode(),
            ]);
        }

        return parent::render($request, $e); // TODO: Change the autogenerated stub
    }
}
